package cn.com.zetatech.maple.core.utils;

import org.apache.commons.configuration2.Configuration;
import org.apache.commons.configuration2.YAMLConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.net.URL;

/**
 * @author carlc
 */
public class ConfigurationManager {
    private static final Logger LOG = LoggerFactory.getLogger(ConfigurationManager.class);

    private static volatile Configuration instance = null;

    private static Configuration from(String fileName) {
        try {
            URL url = null;
            LOG.debug("Looking for {} in classpath", fileName);
            url = ConfigurationManager.class.getClassLoader().getResource(fileName);
            if (url == null) {
                LOG.debug("Looking for /{} in classpath", fileName);
                url = ConfigurationManager.class.getClassLoader().getResource("/" + fileName);
            }
            LOG.debug("Loading {} from {}", fileName, url);
            YAMLConfiguration configuration = new YAMLConfiguration();
            FileInputStream in = new FileInputStream(url.getFile());
            configuration.read(in);
            return configuration;
        } catch (Exception e) {
            throw new RuntimeException("Failed to load " + fileName, e);
        }
    }

    public static Configuration me() {
        if (instance == null) {
            synchronized (ConfigurationManager.class) {
                if (instance == null) {
                    instance = from("application.yml");
                }
            }
        }
        return instance;
    }

}
